<template>
  <div class="cart-container">
    <el-card class="cart-card" shadow="hover">
      <template #header>
        <div class="cart-header">
          <div class="cart-title">
            <el-icon :size="24" color="#409EFF"><ShoppingCart /></el-icon>
            <h2>我的购物车</h2>
            <el-tag type="info" class="cart-count">{{cartArr.length}}件商品</el-tag>
          </div>
          <div class="cart-actions">
            <el-button type="text" @click="clearCart" :disabled="cartArr.length === 0">
              <el-icon><Delete /></el-icon>
              清空购物车
            </el-button>
          </div>
        </div>
      </template>

      <el-table
          :data="cartArr"
          style="width: 100%"
          stripe
          empty-text="购物车空空如也~"
          class="cart-table"
      >
        <el-table-column type="index" label="序号" width="80" align="center">
          <template #default="scope">
            <span class="index-number">{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column label="商品信息" min-width="200">
          <template #default="scope">
            <div class="product-info">
              <el-image
                  :src="scope.row.productImage || 'https://via.placeholder.com/80'"
                  fit="cover"
                  class="product-image"
              ></el-image>
              <div class="product-details">
                <h4 class="product-name">{{ scope.row.productName }}</h4>
                <p class="product-price">¥{{ scope.row.totalPrice }}</p>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="数量" width="150" align="center">
          <template #default="scope">
            <div class="quantity-control">
              <el-button
                  size="small"
                  circle
                  :disabled="scope.row.quantity <= 1"
                  @click="addNum(scope.row.productId, scope.row.quantity - 1)"
              >
                <el-icon><Minus /></el-icon>
              </el-button>
              <span class="quantity">{{ scope.row.quantity }}</span>
              <el-button
                  size="small"
                  circle
                  @click="addNum(scope.row.productId, scope.row.quantity + 1)"
              >
                <el-icon><Plus /></el-icon>
              </el-button>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="选中" width="100" align="center">
          <template #default="scope">
            <el-switch
                v-model="scope.row.selected"
                :active-value="1"
                :inactive-value="0"
                active-color="#409EFF"
                @change="changeSelected(scope.row.productId, scope.row.selected)"
            />
          </template>
        </el-table-column>

        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button
                type="danger"
                size="small"
                @click="deleteCart(scope.row.productId)"
                link
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="cart-footer">
        <div class="total-section">
          <div class="total-price">
            <span>已选商品：</span>
            <span class="selected-count">{{ selectedCount }}件</span>
            <span class="price-label">合计：</span>
            <span class="price-value">¥{{ totalPrice }}</span>
          </div>
          <el-button
              type="primary"
              size="large"
              :disabled="selectedCount === 0"
              class="checkout-btn"
              @click="showBuyDialog"
          >
            去结算
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 结算弹窗 -->
    <el-dialog
        v-model="buyDialogVisible"
        title="确认订单"
        width="50%"
        @close="handleBuyDialogClose"
    >
      <el-form :model="orderForm" label-width="100px">
        <el-form-item label="收货地址" required>
          <el-input v-model="orderForm.shippingAddress" placeholder="请输入收货地址" />
        </el-form-item>
        <el-form-item label="联系电话" required>
          <el-input v-model="orderForm.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="联系人" required>
          <el-input v-model="orderForm.contactName" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="支付方式" required>
          <el-select v-model="orderForm.paymentType" placeholder="请选择支付方式">
            <el-option label="微信支付" :value="1" />
            <el-option label="支付宝" :value="2" />
            <el-option label="银行卡" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <p>运费: ¥{{orderForm.freight.toFixed(2)}}</p>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
              v-model="orderForm.remark"
              type="textarea"
              placeholder="请输入备注信息"
          />
        </el-form-item>
        <!-- 商品信息展示 -->
        <el-form-item label="商品信息" v-if="orderForm.items && orderForm.items.length > 0">
          <div class="product-list-display">
            <div
                v-for="(item, index) in orderForm.items"
                :key="index"
                class="product-item"
            >
              <el-image
                  :src="item.productImage || 'https://via.placeholder.com/80'"
                  fit="cover"
                  class="product-thumbnail"
              ></el-image>
              <div class="product-details">
                <p class="product-name">{{ item.productName }}</p>
                <p class="product-price">单价: ¥{{ item.price.toFixed(2) }}</p>
                <p class="product-quantity">数量: {{ item.quantity }}</p>
                <p class="product-subtotal">小计: ¥{{ (item.price * item.quantity).toFixed(2) }}</p>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="buyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="checkout">确定购买</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  ShoppingCart,
  Delete,
  Plus,
  Minus
} from '@element-plus/icons-vue';
import axios from "axios";

const user = ref(getUser());
const buyDialogVisible = ref(false);
const cartArr = ref([]);
const totalPrice = ref(0);

// 订单表单
const orderForm = ref({
  userId: null,
  merchantId: 0,
  shippingAddress: '',
  contactPhone: '',
  contactName: '',
  remark: '',
  items: [],
  freight: 10,
  paymentType: 1
});

// 弹窗关闭时的处理
const handleBuyDialogClose = () => {
  orderForm.value = {
    userId: user.value.id,
    merchantId: 0,
    shippingAddress: '',
    contactPhone: '',
    contactName: '',
    remark: '',
    items: [],
    freight: 10,
    paymentType: 1
  };
};

// 计算已选商品数量
const selectedCount = computed(() => {
  return cartArr.value.filter(item => item.selected === 1).length;
});

// 显示结算弹窗
const showBuyDialog = () => {
  const selectedItems = cartArr.value.filter(item => item.selected === 1);

  if (selectedItems.length === 0) {
    ElMessage.warning('请至少选择一件商品');
    return;
  }

  // 初始化订单表单
  orderForm.value = {
    userId: user.value.id,
    merchantId: 0,
    shippingAddress: '',
    contactPhone: '',
    contactName: '',
    remark: '',
    items: selectedItems.map(item => ({
      productId: item.productId,
      productName: item.productName,
      productImage: item.productImage,
      quantity: item.quantity,
      price: parseFloat(item.totalPrice)
    })),
    freight: 10,
    paymentType: 1
  };

  buyDialogVisible.value = true;
};

// 结算方法
const checkout = async () => {
  try {
    // 1. 获取已选中的商品
    const selectedItems = cartArr.value.filter(item => item.selected === 1);

    if (selectedItems.length === 0) {
      ElMessage.warning('请至少选择一件商品');
      return;
    }

    // 2. 检查商品是否来自同一个商家
    const merchantIds = [...new Set(selectedItems.map(item => item.merchantId))];

    // 3. 如果多个商家，询问用户是否要分开下单
    if (merchantIds.length > 1) {
      try {
        await ElMessageBox.confirm(
            `您选择的商品来自 ${merchantIds.length} 个不同商家，将为您创建 ${merchantIds.length} 个订单，是否继续？`,
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
        );
      } catch {
        return;
      }
    }

    // 4. 准备订单数据
    const orders = merchantIds.map(merchantId => {
      const merchantItems = selectedItems.filter(item => item.merchantId === merchantId);
      return {
        userId: user.value.id,
        merchantId,
        shippingAddress: orderForm.value.shippingAddress,
        contactPhone: orderForm.value.contactPhone,
        contactName: orderForm.value.contactName,
        remark: orderForm.value.remark,
        items: merchantItems.map(item => ({
          productId: item.productId,
          productName: item.productName,
          productImage: item.productImage,
          quantity: item.quantity,
          price: parseFloat(item.totalPrice)
        })),
        freight: orderForm.value.freight,
        paymentType: orderForm.value.paymentType
      };
    });

    // 5. 提交订单
    const results = await Promise.all(
        orders.map(order =>
            axios.post(BASE_URL + '/api/v1/order/private/create', order)
        )
    );

    // 6. 处理结果
    const allSuccess = results.every(res => res.data.code === 2000);
    if (allSuccess) {
      ElMessage.success(`成功创建${results.length}个订单`);
      buyDialogVisible.value = false;
      loadProducts(); // 刷新购物车
    } else {
      const errorMessages = results
          .filter(res => res.data.code !== 2000)
          .map(res => res.data.msg)
          .join('; ');
      ElMessage.error(`部分订单创建失败: ${errorMessages}`);
    }
  } catch (error) {
    ElMessage.error('下单失败: ' + error.message);
  }
};

// 加载购物车商品
const loadProducts = () => {
  axios.get(BASE_URL+'/api/v1/cart/select').then((response) => {
    if (response.data.code == 2000) {
      cartArr.value = response.data.data;
      // 加载购物车商品的详细信息
      for (let i = 0; i < cartArr.value.length; i++){
        axios.get(BASE_URL+'/api/v1/product/detail', {
          params: { id: cartArr.value[i].productId }
        }).then((response) => {
          if (response.data.code == 2000) {
            const productData = response.data.data;
            cartArr.value[i].productName = productData.name || '未知商品';
            cartArr.value[i].productImage = productData.imageUrls || 'https://via.placeholder.com/80';
            cartArr.value[i].merchantId = productData.merchantId || 0;
          }
        });
      }
    } else {
      ElMessage.error("购物车商品加载失败,"+response.data.msg);
    }
  });
};

// 修改商品选中状态
const changeSelected = (productId, selected) => {
  axios.post(BASE_URL+'/api/v1/cart/update', {
    productId,
    selected
  }).then((response) => {
    if (response.data.code == 2000) {
      loadProducts();
      allPrice();
    } else {
      ElMessage.error(response.data.msg);
    }
  });
};

// 移除购物车商品
const deleteCart = (productId) => {
  ElMessageBox.confirm('确定要删除该商品吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    axios.post(BASE_URL+'/api/v1/cart/delete/'+productId).then((response) => {
      if (response.data.code == 2000) {
        ElMessage.success('删除成功');
        loadProducts();
        allPrice();
      } else {
        ElMessage.error(response.data.msg);
      }
    });
  }).catch(() => {});
};

// 清空购物车
const clearCart = () => {
  ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    axios.post(BASE_URL+'/api/v1/cart/delete/0').then((response) => {
      if (response.data.code == 2000) {
        ElMessage.success('购物车已清空');
        cartArr.value = [];
        totalPrice.value = 0;
      } else {
        ElMessage.error(response.data.msg);
      }
    });
  }).catch(() => {});
};

// 修改商品数量
const addNum = (productId, quantity) => {
  if (quantity <= 0) {
    deleteCart(productId);
    return;
  }
  axios.post(BASE_URL+'/api/v1/cart/update', {
    productId,
    quantity
  }).then((response) => {
    if (response.data.code == 2000) {
      loadProducts();
      allPrice();
    } else {
      ElMessage.error(response.data.msg);
    }
  });
};

// 计算选中商品总价
const allPrice = () => {
  axios.get(BASE_URL+'/api/v1/cart/AllPrice').then((response) => {
    if (response.data.code == 2000) {
      totalPrice.value = response.data.data;
    } else {
      ElMessage.error("总价加载失败"+response.data.msg);
    }
  });
};

onMounted(() => {
  loadProducts();
  allPrice();
});
</script>

<style scoped>
.cart-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.cart-card {
  border-radius: 12px;
  overflow: hidden;
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.cart-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.cart-title h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.cart-count {
  margin-left: 10px;
}

.cart-actions {
  display: flex;
  gap: 10px;
}

.cart-table {
  margin-top: 10px;
}

.index-number {
  display: inline-block;
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  background-color: #f5f7fa;
  border-radius: 50%;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.product-image {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  border: 1px solid #eee;
}

.product-details {
  flex: 1;
}

.product-name {
  margin: 0 0 5px 0;
  font-size: 16px;
  color: #333;
}

.product-price {
  margin: 0;
  font-size: 16px;
  color: #f56c6c;
  font-weight: bold;
}

.quantity-control {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
}

.quantity {
  min-width: 30px;
  text-align: center;
}

.cart-footer {
  margin-top: 20px;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.total-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-price {
  font-size: 16px;
}

.selected-count {
  color: #409EFF;
  font-weight: bold;
  margin-right: 20px;
}

.price-label {
  color: #666;
}

.price-value {
  font-size: 24px;
  color: #f56c6c;
  font-weight: bold;
  margin-left: 5px;
}

.checkout-btn {
  width: 180px;
  height: 50px;
  font-size: 16px;
}

/* 商品列表样式 */
.product-list-display {
  width: 100%;
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 10px;
  max-height: 300px;
  overflow-y: auto;
}

.product-item {
  display: flex;
  align-items: center;
  padding: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.product-item:last-child {
  border-bottom: none;
}

.product-thumbnail {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  margin-right: 15px;
}

.product-details {
  flex: 1;
}

.product-name {
  margin: 0 0 5px 0;
  font-size: 14px;
  color: #333;
  font-weight: bold;
}

.product-price,
.product-quantity,
.product-subtotal {
  margin: 3px 0;
  font-size: 13px;
  color: #666;
}

.product-subtotal {
  color: #f56c6c;
  font-weight: bold;
}

@media (max-width: 768px) {
  .cart-container {
    padding: 0 10px;
  }

  .product-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .product-image {
    width: 60px;
    height: 60px;
  }

  .total-section {
    flex-direction: column;
    gap: 15px;
    align-items: flex-end;
  }
}
</style>